import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/bezier_bounce_footer.dart';
import 'package:flutter_easyrefresh/bezier_circle_header.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/api/service/user_service.dart';
import 'package:hm_show_flutter/entity/course_list_entity.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/widgets/empty_view.dart';
import 'package:hm_show_flutter/widgets/loading_dialog.dart';

///课程列表
class CourseListPage extends StatefulWidget {
  @override
  _CourseListPageState createState() => _CourseListPageState();
}

class _CourseListPageState extends State<CourseListPage> {
  UserService _service = new UserService();
  List<CourseListDataList> _list;

  bool isLoading;
  int _pageTotal; //总页数
  int _pageCurrent = 1; //当前页

  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    super.initState();
    getGoodsListData(false);
  }

  void getGoodsListData(bool isLoadMore) {
    if (isLoadMore) {
      //加载更多
      if (_pageCurrent >= _pageTotal) {
        ToastUtil.showToast("没有更多课程了~");
        _controller.finishLoad();
        return;
      }
      _pageCurrent++;
    } else {
      _pageCurrent = 1;
    }

    isLoading = true;
    _service.getCourseListData(_pageCurrent, (success) {
      CourseListEntity entity = success;
      try {

        setState(() {
          isLoading = false;
          _pageTotal = entity.data.pages;
          if (isLoadMore) {
            _controller.finishLoad();
            _list.addAll(entity.data.xList);
          } else {
            _controller.finishRefresh();
            _list = entity.data.xList;
          }
        });
        _controller.finishLoad();
      } catch (e, s) {
        print(s);
      }
    }, onFail: (fail) {
      if (isLoadMore) {
        _controller.finishLoad();
      } else {
        _controller.finishRefresh();
      }
      setState(() {
        isLoading = false;
      });
      _controller.finishLoad();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            iconTheme: IconThemeData(color: Colors.white),
            automaticallyImplyLeading: true,
            centerTitle: true,
            title: Text(
              "课程列表",
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
          preferredSize: Size.fromHeight(ScreenUtil.instance.height * 0.036)),
      body: _getContentView(),

    );
  }

  Widget _getContentView() {
    if (isLoading) {
      return LoadingDialog();
    } else if (_list == null || _list.isEmpty) {
      return EmptyView(
        onRetry: () {
          getGoodsListData(false);
        },
      );
    } else {
      return Container(
        child: EasyRefresh(
          controller: _controller,
          header: BezierCircleHeader(backgroundColor: AppColors.mainColor),
          footer: BezierBounceFooter(backgroundColor: AppColors.mainColor),
          enableControlFinishRefresh: true,
          enableControlFinishLoad: false,
          child: SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.all(5.0),
              child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: _list.length,
                  physics: NeverScrollableScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return _getGridViewItem(context, _list[index]);
                  }),
            ),
          ),
          onRefresh: () async {
            getGoodsListData(false);
          },
          onLoad: () async {
            getGoodsListData(true);
          },
        ),
      );
    }
  }

  Widget _getGridViewItem(BuildContext context, CourseListDataList entity) {
    return Container(
      child: InkWell(
        onTap: () {
          NavigatorUtils.goGoodsDetailPage(context, entity.id);
        },
        child: Card(
          elevation: 2.0,
          margin: EdgeInsets.all(6.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 4.0, top: 4.0),
                alignment: Alignment.center,
                child: Text(
                  entity.name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.black54, fontSize: 14.0),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 4.0),
              ),
              Html(data: entity.description),
            ],
          ),
        ),
      ),
    );
  }
}
